/**
 * 需求评论相关JavaScript
 */

var currentCommentIssueId = null;
var currentUserId = null;
var currentUser = null;

// 页面加载完成后初始化用户信息
$(document).ready(function() {
    // 从全局变量或页面元素中获取当前用户信息
    currentUserId = typeof curUserId !== 'undefined' ? curUserId : null;
    currentUser = typeof curUser !== 'undefined' ? curUser : null;
});

/**
 * 初始化评论区域
 */
function initComments(issueId) {
    currentCommentIssueId = issueId;
    loadComments(issueId);
}

/**
 * 加载评论列表
 */
function loadComments(issueId) {
    $('#commentsList').html('<div class="text-center"><i class="fa fa-spinner fa-spin"></i> 正在加载评论...</div>');
    
    $.ajax({
        url: ctx + 'project/issue/comment/list/' + issueId,
        type: 'POST',
        success: function(result) {
            if (result.code == 0) {
                displayComments(result.data);
            } else {
                $('#commentsList').html('<div class="alert alert-danger">加载评论失败: ' + result.msg + '</div>');
            }
        },
        error: function() {
            $('#commentsList').html('<div class="alert alert-danger">网络错误，加载评论失败</div>');
        }
    });
}

/**
 * 显示评论列表
 */
function displayComments(comments) {
    if (!comments || comments.length === 0) {
        $('#commentsList').html('<div class="alert alert-info">暂无评论</div>');
        return;
    }
    
    var html = '';
    
    // 按照父评论和子评论分组
    var parentComments = comments.filter(comment => comment.parentId == null);
    
    parentComments.forEach(function(parent) {
        html += renderComment(parent, 0);
        
        // 获取子评论
        var childComments = comments.filter(comment => comment.parentId == parent.id);
        childComments.forEach(function(child) {
            html += renderComment(child, 1);
        });
    });
    
    $('#commentsList').html(html);
}

/**
 * 渲染单个评论
 */
function renderComment(comment, level) {
    var marginLeft = level * 40; // 子评论缩进
    var isOwner = comment.userId == currentUserId;
    var isAdmin = currentUser && currentUser.admin;
    
    var html = '<div class="comment-item" style="margin-left: ' + marginLeft + 'px; margin-bottom: 15px; border-left: 2px solid #eee; padding-left: 15px;">';
    html += '<div class="comment-header">';
    
    // 用户头像和名称
    html += '<div class="pull-left" style="margin-right: 10px;">';
    if (comment.userAvatar && comment.userAvatar != '') {
        html += '<img src="' + comment.userAvatar + '" class="img-circle" width="32" height="32">';
    } else {
        html += '<div class="img-circle bg-info" style="width: 32px; height: 32px; display: flex; align-items: center; justify-content: center; color: white;">';
        html += comment.userName ? comment.userName.charAt(0).toUpperCase() : 'U';
        html += '</div>';
    }
    html += '</div>';
    
    // 评论信息
    html += '<div class="comment-meta">';
    html += '<strong>' + (comment.userName || '未知用户') + '</strong>';
    html += ' <small class="text-muted">' + formatDateTime(comment.createTime) + '</small>';
    
    // 内部评论标记
    if (comment.isInternal == 1) {
        html += ' <span class="label label-warning">内部</span>';
    }
    
    // 操作按钮
    if (isOwner || isAdmin) {
        html += '<div class="pull-right">';
        html += '<button class="btn btn-xs btn-default" onclick="editComment(' + comment.id + ')"><i class="fa fa-edit"></i></button>';
        html += ' <button class="btn btn-xs btn-danger" onclick="deleteComment(' + comment.id + ')"><i class="fa fa-trash"></i></button>';
        html += '</div>';
    }
    
    html += '</div>';
    html += '</div>';
    
    // 评论内容
    html += '<div class="comment-content" style="margin-top: 10px;">';
    html += '<div id="comment-content-' + comment.id + '">' + comment.content + '</div>';
    
    // 编辑框（默认隐藏）
    html += '<div id="comment-edit-' + comment.id + '" style="display: none;">';
    html += '<textarea class="form-control" rows="3" id="comment-text-' + comment.id + '">' + comment.content + '</textarea>';
    html += '<div class="text-right" style="margin-top: 5px;">';
    html += '<button class="btn btn-xs btn-primary" onclick="saveComment(' + comment.id + ')">保存</button>';
    html += ' <button class="btn btn-xs btn-default" onclick="cancelEdit(' + comment.id + ')">取消</button>';
    html += '</div>';
    html += '</div>';
    html += '</div>';
    
    // 附件列表
    if (comment.attachments && comment.attachments.length > 0) {
        html += '<div class="comment-attachments" style="margin-top: 10px;">';
        html += '<i class="fa fa-paperclip"></i> 附件: ';
        
        comment.attachments.forEach(function(attachment) {
            html += '<a href="' + ctx + 'common/download?fileName=' + attachment.filePath + '" class="btn btn-xs btn-default" style="margin-right: 5px;">';
            html += '<i class="fa fa-download"></i> ' + attachment.fileName;
            html += '</a>';
        });
        
        html += '</div>';
    }
    
    // 回复按钮
    if (level === 0) {
        html += '<div class="comment-actions" style="margin-top: 10px;">';
        html += '<button class="btn btn-xs btn-default" onclick="replyComment(' + comment.id + ', \'' + comment.userName + '\')">';
        html += '<i class="fa fa-reply"></i> 回复';
        html += '</button>';
        html += '</div>';
    }
    
    html += '</div>';
    
    return html;
}

/**
 * 添加评论
 */
function addComment(parentId, parentUserName) {
    var content = parentId ? $('#reply-content-' + parentId).val() : $('#newCommentContent').val();
    
    if (!content.trim()) {
        layer.msg('评论内容不能为空', {icon: 2});
        return;
    }
    
    var comment = {
        issueId: currentCommentIssueId,
        content: content,
        parentId: parentId || null
    };
    
    $.ajax({
        url: ctx + 'project/issue/comment/add',
        type: 'POST',
        data: comment,
        success: function(result) {
            if (result.code == 0) {
                layer.msg('评论发表成功', {icon: 1});
                
                if (parentId) {
                    $('#reply-form-' + parentId).remove();
                } else {
                    $('#newCommentContent').val('');
                }
                
                loadComments(currentCommentIssueId);
            } else {
                layer.msg('评论发表失败: ' + result.msg, {icon: 2});
            }
        },
        error: function() {
            layer.msg('网络错误，评论发表失败', {icon: 2});
        }
    });
}

/**
 * 回复评论
 */
function replyComment(parentId, parentUserName) {
    // 检查是否已经有回复框
    var replyFormId = 'reply-form-' + parentId;
    if ($('#' + replyFormId).length > 0) {
        $('#' + replyFormId).remove();
        return;
    }
    
    var html = '<div id="' + replyFormId + '" style="margin-top: 10px; margin-left: 40px; border-left: 2px solid #eee; padding-left: 15px;">';
    html += '<div class="form-group">';
    html += '<textarea id="reply-content-' + parentId + '" class="form-control" rows="3" placeholder="回复 ' + parentUserName + '..."></textarea>';
    html += '</div>';
    html += '<div class="form-group">';
    html += '<button class="btn btn-xs btn-primary" onclick="addComment(' + parentId + ', \'' + parentUserName + '\')">回复</button>';
    html += ' <button class="btn btn-xs btn-default" onclick="$(\'#' + replyFormId + '\').remove()">取消</button>';
    html += '</div>';
    html += '</div>';
    
    // 添加到评论后面
    var parentComment = $('.comment-item').has('[id^="comment-content-' + parentId + '"]');
    if (parentComment.length > 0) {
        parentComment.after(html);
    } else {
        // 如果找不到父评论，添加到评论列表底部
        $('#commentsList').append(html);
    }
    
    // 自动聚焦到回复框
    $('#reply-content-' + parentId).focus();
}

/**
 * 编辑评论
 */
function editComment(commentId) {
    $('#comment-content-' + commentId).hide();
    $('#comment-edit-' + commentId).show();
}

/**
 * 保存评论
 */
function saveComment(commentId) {
    var content = $('#comment-text-' + commentId).val();
    
    if (!content.trim()) {
        layer.msg('评论内容不能为空', {icon: 2});
        return;
    }
    
    var comment = {
        id: commentId,
        content: content
    };
    
    $.ajax({
        url: ctx + 'project/issue/comment/edit',
        type: 'POST',
        data: comment,
        success: function(result) {
            if (result.code == 0) {
                layer.msg('评论修改成功', {icon: 1});
                loadComments(currentCommentIssueId);
            } else {
                layer.msg('评论修改失败: ' + result.msg, {icon: 2});
            }
        },
        error: function() {
            layer.msg('网络错误，评论修改失败', {icon: 2});
        }
    });
}

/**
 * 取消编辑
 */
function cancelEdit(commentId) {
    $('#comment-content-' + commentId).show();
    $('#comment-edit-' + commentId).hide();
}

/**
 * 删除评论
 */
function deleteComment(commentId) {
    layer.confirm('确定要删除这条评论吗？', {
        icon: 3,
        title: '确认删除'
    }, function(index) {
        $.ajax({
            url: ctx + 'project/issue/comment/remove',
            type: 'POST',
            data: { ids: commentId },
            success: function(result) {
                layer.close(index);
                if (result.code == 0) {
                    layer.msg('评论删除成功', {icon: 1});
                    loadComments(currentCommentIssueId);
                } else {
                    layer.msg('评论删除失败: ' + result.msg, {icon: 2});
                }
            },
            error: function() {
                layer.close(index);
                layer.msg('网络错误，评论删除失败', {icon: 2});
            }
        });
    });
}

/**
 * 清空评论内容
 */
function clearComment() {
    $('#newCommentContent').val('');
}

/**
 * 刷新评论列表
 */
function refreshComments() {
    loadComments(currentCommentIssueId);
}

/**
 * 格式化日期时间
 */
function formatDateTime(dateTimeStr) {
    if (!dateTimeStr) return '';
    
    var date = new Date(dateTimeStr);
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hours = date.getHours();
    var minutes = date.getMinutes();
    
    return year + '-' + (month < 10 ? '0' + month : month) + '-' + (day < 10 ? '0' + day : day) + ' ' +
           (hours < 10 ? '0' + hours : hours) + ':' + (minutes < 10 ? '0' + minutes : minutes);
}